package cn.hl.hm.handler;

import java.io.BufferedReader;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import com.alipay.api.AlipayConstants;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.demo.trade.config.Configs;
import com.vizhuo.utils.DateUtil;

import cn.hl.hm.constants.OrderStatus;
import cn.hl.hm.constants.PayMethod;
import cn.hl.hm.dao.RoadFeeMapper;
import cn.hl.hm.entity.RoadFee;
import cn.hl.hm.entity.UnifiedOrderRespose;
import cn.hl.hm.service.PushToAppIService;
import cn.hl.hm.util.alipayJs.AlipayCore;

/**
 * 支付宝APP支付handler
 * 
 * @author 大和
 *
 */
@Service
public class ZfbScanPayHandler extends PayHandler {

	private static final Logger logger = Logger.getLogger(ZfbAppPayHandler.class);

	
	@Autowired
	private RoadFeeMapper roadFeeMapper;

	@Autowired
	@Qualifier("pushToAppServiceImpl")
	private PushToAppIService pushToAppIService;

	/**
	 * 处理支付宝支付请求
	 */
	@Override
	public Map<String, String> handler(Map<String, String> payMap) {
		return null;
		
	}
	@Override
	protected void initHandler() {
		register(PayMethod.ROAD_ZFB_SCAN_MER, ZfbScanPayHandler.class);
	}

	/**
	 * 回调请求
	 */
	@Override
	public Boolean callback(HttpServletRequest request, HttpServletResponse response) {
		try {
			logger.info("......[支付宝回调]开始......" );
			
			BufferedReader reader = request.getReader();
			String line = "";
			StringBuffer inputString = new StringBuffer();
			while ((line = reader.readLine()) != null) {
				inputString.append(line);
			}
			if (reader != null) {
				reader.close();
			}
			logger.info("......[支付宝回调]接收到的报文......" + inputString.toString());
			//String decode = URLDecoder.decode(inputString.toString());
			String decode =URLDecoder.decode(inputString.toString(), "utf-8");
			//URL解码
			logger.info("......[支付宝回调]接收到的报文URLDecoder解码后......" + decode);
			//编码 (不加这行会有乱码)
			String str = new String(decode.getBytes("UTF-8"), "utf-8");
			logger.info("......[支付宝回调]接收到的报文UTF-8->UTF-8解码后......" + str);
			
			Map<String, String> map = AlipayCore.str2map(str);
			
			
			
			String OrderInfoCode = map.get("out_trade_no");// 商户网站唯一订单号
			String userPaymentTime = map.get("gmt_payment");// 支付时间
			String paymentFlowAccount = map.get("trade_no");// 流水账号支付宝交易号
			String paymentNo = map.get("buyer_logon_id");// 支付账号买家支付宝账号
			String sign = map.get("sign");
			//查看订单
			RoadFee orderInfo = new RoadFee();
			orderInfo.setOrderCode(OrderInfoCode);
			List<RoadFee> selectPageList = roadFeeMapper.selectRoadFees(orderInfo);
			//解決paramError
			if(selectPageList!=null&&selectPageList.size()>0){
				
			}else {
				return false;
			}
			//app扫码支付
			Configs.init("zfbinfo.properties");				//验证签名
			/*boolean rsaCheckContent = AlipaySignature.rsaCheckV1(map, Configs.getAlipayPublicKey(), "UTF-8",AlipayConstants.SIGN_TYPE_RSA2);

			if(!rsaCheckContent){
				return false;
			}*/
			
			 
			if(!map.get("trade_status").equalsIgnoreCase("TRADE_SUCCESS")){
				return false;
			}
			logger.info("......[支付宝验签结果成功]+[交易状态成功]......");
			UnifiedOrderRespose unifiedOrderRespose = new UnifiedOrderRespose();
			unifiedOrderRespose.setTime_end(userPaymentTime);
			unifiedOrderRespose.setTransaction_id(paymentFlowAccount);
			unifiedOrderRespose.setOpenid(paymentNo);
			unifiedOrderRespose.setOut_trade_no(OrderInfoCode);
			unifiedOrderRespose.setSign(sign);
			return processBusiness( unifiedOrderRespose);
		} catch (Exception ex) {
			ex.printStackTrace();
			return false;

		}

	}

	private Boolean processBusiness(UnifiedOrderRespose unifiedOrderRespose) {
		// 查订单
		RoadFee orderInfo = new RoadFee();
		orderInfo.setOrderCode(unifiedOrderRespose.getOut_trade_no());
		List<RoadFee> selectPageList = roadFeeMapper.selectRoadFees(orderInfo);
		//解決paramError
		if(selectPageList!=null&&selectPageList.size()>0){
			
		}else {
			return false;
		}
		
		if (selectPageList != null && selectPageList.size() > 0) {
			RoadFee order  = selectPageList.get(0);
			logger.info("......[支付宝回调]开始处理业务......unifiedOrderRespose"+unifiedOrderRespose.toString());

			if (order.getOrderStatus().equals("1")) {
				String userPaymentTime = unifiedOrderRespose.getTime_end();// 支付时间
				logger.info("支付时间" + userPaymentTime);
				if (userPaymentTime != null && !("null".equals(userPaymentTime))) {

				} else {
					userPaymentTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
				}
				Date string2Date = DateUtil.string2Date(userPaymentTime, "yyyy-MM-dd HH:mm:ss");
				logger.info("......转换后支付时间" + string2Date);

				// 1 修改订单
				RoadFee OrderInfoUpParam = new RoadFee();
				OrderInfoUpParam.setId(order.getId());
				OrderInfoUpParam.setOrderStatus("2");
				OrderInfoUpParam.setPayTime(string2Date);
				OrderInfoUpParam.setPaymentNo(unifiedOrderRespose.getOpenid());
				OrderInfoUpParam.setPayTransNo(unifiedOrderRespose.getTransaction_id());
				OrderInfoUpParam.setPayType(PayMethod.ROAD_ZFB_SCAN_MER.getCode());
				logger.info("......[支付宝回调]更新订单参数......OrderInfoUpParam"+OrderInfoUpParam.toString());
				int updateOrderInfoById = roadFeeMapper.updateByPrimaryKey(OrderInfoUpParam);
				if (updateOrderInfoById > 0) {
					return true;
				} else {
					return false;
				}

			} else {
				return true;
			}

		} else {
			return false;
		}
	}

}
